#pragma once

class CStroke
{
public:
	virtual ~CStroke()
	{
		while (mPoints.GetSize() > 0)
		{
			CPoint* pt = (CPoint*)mPoints.RemoveHead();
			delete pt;
		}
	}
	void addPoint(CPoint* pt)
	{
		mPoints.AddTail(pt);
	}

	CPtrList mPoints;
};

class ScribbleCanvas : public AWTCanvas, public AWTMouseListener, public AWTMouseMotionListener
{
public:
	ScribbleCanvas(void)
	{
		mStroke = NULL;
		addMouseListener(this);
		addMouseMotionListener(this);
	}
	~ScribbleCanvas(void)
	{
		while (mStrokes.GetSize() > 0)
		{
			CStroke* pStroke = (CStroke*)mStrokes.RemoveHead();
			delete pStroke;
		}
	}

	virtual void mouseClicked(AWTMouseEvent* e)
	{
	}
	virtual void mousePressed(AWTMouseEvent* e)
	{
		if (mStroke == NULL)
		{
			mStroke = new CStroke();
			mStroke->addPoint(new CPoint((POINT)e->getPoint()));
		}
	}
	virtual void mouseReleased(AWTMouseEvent* e)
	{
		if (mStroke != NULL)
		{
			mStroke->addPoint(new CPoint((POINT)e->getPoint()));
			mStrokes.AddTail(mStroke);
			mStroke = NULL;
		}
	}
	virtual void mouseEntered(AWTMouseEvent* e){}
	virtual void mouseExited(AWTMouseEvent* e){}

	virtual void mouseDragged(AWTMouseEvent* e)
	{
		if (mStroke != NULL)
		{
			CDC* pDC = getGraphics();
			if (pDC != NULL)
			{
				CPoint* pt = (CPoint*)mStroke->mPoints.GetTail();
				pDC->MoveTo((POINT)*pt);
				pDC->LineTo((POINT)e->getPoint());
			}
			mStroke->addPoint(new CPoint((POINT)e->getPoint()));
		}
	}
	virtual void mouseMoved(AWTMouseEvent* e)
	{
	}

	virtual void paint(CDC* pDC)
	{
		CPoint* pt = NULL;
		POSITION pos = mStrokes.GetHeadPosition();
		while (pos != NULL)
		{
			CStroke* stroke = (CStroke*)mStrokes.GetNext(pos);
			POSITION pos2 = stroke->mPoints.GetHeadPosition();
			if (pos2 != NULL)
			{
				pt = (CPoint*)stroke->mPoints.GetNext(pos2);
				pDC->MoveTo((POINT)*pt);
				while (pos2 != NULL)
				{
					pt = (CPoint*)stroke->mPoints.GetNext(pos2);
					pDC->LineTo((POINT)*pt);
				}
			}
		}

	}

	CPtrList mStrokes;
	CStroke* mStroke;
};
